/*
 * This file is part of ksPlatform
 * 
 * Copyright (c) 2014-2015
 * 
 * This file is dual-licensed under the AGPLv3 (http://www.gnu.org/licenses/agpl-3.0.html) 
 * 
 * If you are unsure which license is appropriate for your use, please contact the sales department
 * at 97041437@qq.com.
 */
package cn.com.ksplatform.modules.autocode.sdk.v1.db;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;


/**
 * ClassName:DbMetadata.java <br/>
 * Date: 2015年12月28日 <br/>
 * 数据库元数据信息获取
 * @author Mr.Xiao
 * @version 1.0
 */
@Component("autocode.sdk.db")
public class DbMetadata {
	@Autowired
	@Qualifier("jdbcTemplate")
	private JdbcTemplate jdbcTemplate;
	
	private Connection _conn;
	
	public Connection getConn() {
		try {
			if(_conn == null || _conn.isClosed()){
				try {
					_conn = jdbcTemplate.getDataSource().getConnection();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return _conn;
	}

	public DatabaseMetaData getDatabaseMetadata() throws SQLException{
		DatabaseMetaData dmd = getConn().getMetaData();
		return dmd;
	}
	
	public Object getTable(HttpServletRequest req,HttpServletResponse rep) throws SQLException{
		Connection conn = getConn();
		DatabaseMetaData dtd = this.getDatabaseMetadata();
		ResultSet rt = dtd.getTables(conn.getCatalog(), null, null, new String[]{"TABLE"});
		int clmCnt = rt.getMetaData().getColumnCount();
		List<Map<String, Object>> tables = new ArrayList<Map<String,Object>>();
		while(rt.next()){
			Map<String,Object> map = new HashMap<String,Object>();
			for(int i=1;i<=clmCnt;i++){
				map.put(rt.getMetaData().getColumnName(i), rt.getObject(i));
			}
			tables.add(map);
		}
		return tables;
	}
	
	public Object getColumns(HttpServletRequest req,HttpServletResponse rep) throws SQLException{
		String table = req.getParameter("table");
		
		
		if(!StringUtils.hasText(table)){
			return null;
		}
		
		DatabaseMetaData dtd = this.getDatabaseMetadata();
		Connection conn = getConn();
		ResultSet rt = dtd.getColumns(conn.getCatalog(), null, table, null);
		int clmCnt = rt.getMetaData().getColumnCount();
		List<Map<String, Object>> tables = new ArrayList<Map<String,Object>>();
		while(rt.next()){
			Map<String,Object> map = new HashMap<String,Object>();
			for(int i=1;i<=clmCnt;i++){
				map.put(rt.getMetaData().getColumnName(i), rt.getObject(i));
			}
			tables.add(map);
		}
		return tables;
	}
}
